import axios from 'axios'
import { Message } from 'element-ui'
import { tansParams } from "@/utils/common";

const duration = 5 * 1000; // 消息显示时间
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 60 * 1000
})

// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  let token = localStorage.getItem('token')
  if (token && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + token
  }
  if (config.method === 'get' && config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.status || 200;
    if (res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      return Message({ message: '登录已过期，请重新登录。', type: 'error', duration })
    } else if (code !== 200) {
      return Message({ message: '服务异常，请稍后再试', type: 'error', duration })
    } else {
      if (res.data.code != 1) {
        Message({ message: res.data.msg, type: 'error', duration })
      }
      return res.data
    }
  },
  error => {
    let { message } = error;
    if (message == "Network Error") {
      message = "网络异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    return Message({ message: message, type: 'error', duration })
  }
)

export default service
